"""
Frame for binary input.
"""

import tkinter as tk
from ui.DataProvidingFrame import DataProvidingFrame
from ui.ByteGenToBitGen import byteGeneratorToBit

class CrcBinaryInputFrame(DataProvidingFrame):
    """This frame contains the interaction needed for the user to calculate
    the CRC from binary input."""

    def get_help_message(self):
        return """The input must be a valid binary data (with only 0 and 1)."""

    def getDataGenerator(self):
        """Override from DataProvidingFrame.
        Return a generator (or None) for the data."""
        if not self.data_is_valid():
            return None

        data = self.inputBox.get(1.0,tk.END)
        def gen():
            for i in data[:-1]:
                yield int(i)
        return gen()

    def getDataSize(self):
        """Override from DataProvidingFrame.
        Return the size of the data."""
        data = self.inputBox.get(1.0,tk.END)
        return len(data)-1

    def data_is_valid(self):
        """Check that the input is valid, that is to say
        the data contains only 0 and 1 for binary.
        Return True if the input is valid."""
        data = self.inputBox.get(1.0,tk.END)[:-1]
        for i in data:
            if i!='0' and i!='1':
                return False
        return True

    def create_input_instructions(self):
        """Create the message widget."""
        self.description = tk.Message(self)
        self.description["width"] = "180" # pixels
        self.description["text"] = "Please give a binary string:"
        self.description["anchor"] = "w"
        self.description.pack({"side":"top","padx":5,"pady":5,"fill":"x"})
    def create_input_box(self):
        """Create the text widget."""
        def cb(event):
            if self.data_is_valid():
                self.inputBox['bg'] = '#ffffff'
                self.inputBox['fg'] = '#000000'
            else:
                self.inputBox['bg'] = '#ee0011'
                self.inputBox['fg'] = '#ffffff'
            self.inputBox.edit_modified(False) # Is needed for the next callback.

        self.inputBox = tk.Text(self)
        self.inputBox["width"] = "35" # columns
        self.inputBox["height"] = "3" # lines
        self.inputBox.pack({"side":"bottom","padx":5,"pady":5,"fill":"both","expand":1})
        self.inputBox.bind('<<Modified>>',cb)
    def create_widgets(self):
        """Create the frame starting layout."""
        self.create_input_instructions()
        self.create_input_box()
    def __init__(self,master=None,size=(100,100)):
        super().__init__(master,size)
        self.create_widgets()
        super().create_widgets()
